package com.harmony.volley.sample.ui.itemprovider;

import com.harmony.volley.sample.ResourceTable;
import com.harmony.volley.sample.model.HomeArticleModel;
import com.harmony.volley.sample.util.TextUtils;
import me.drakeet.multitype.ItemViewBinder;
import me.drakeet.multitype.ItemViewHolder;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import org.apache.commons.lang.StringEscapeUtils;

/**
 * 首页文章列表条目
 */
public class HomeArticleItemViewBinder extends ItemViewBinder<HomeArticleModel.PageModel.ItemModel, HomeArticleItemViewBinder.ViewHolder> {
    @Override
    protected ViewHolder onCreateViewHolder(LayoutScatter scatter, ComponentContainer parent) {
        return new ViewHolder(scatter.parse(ResourceTable.Layout_item_home_article, parent, false));
    }

    @Override
    protected void onBindViewHolder(ViewHolder holder, HomeArticleModel.PageModel.ItemModel itemModel) {
        if (!TextUtils.isEmpty(itemModel.getTitle())) {
            //json里面有一些特殊符号，特殊符号会被gson转义，
            //StringEscapeUtils可以对转义的字符串进行反转义
            //调用StringEscapeUtils的unescapeHtml方法，如果字符串中没有转义字符，
            //unescapeHtml方法会直接返回原字符串，否则会对字符串进行反转义。
            String title = StringEscapeUtils.unescapeHtml(itemModel.getTitle());
            //标题
            holder.vTitle.setText(title);
        } else {
            holder.vTitle.setText("");
        }
        String name;
        if (!TextUtils.isEmpty(itemModel.getAuthor())) {
            name = itemModel.getAuthor();
        } else {
            name = itemModel.getShareUser();
        }
        //姓名
        holder.vUserName.setText(name);
        //日期
        holder.vDate.setText(itemModel.getNiceShareDate());
    }

    static class ViewHolder extends ItemViewHolder {
        private final Text vTitle;
        private final Text vUserName;
        private final Text vDate;

        public ViewHolder(Component itemView) {
            super(itemView);
            vTitle = (Text) itemView.findComponentById(ResourceTable.Id_title);
            vUserName = (Text) itemView.findComponentById(ResourceTable.Id_user_name);
            vDate = (Text) itemView.findComponentById(ResourceTable.Id_date);
        }
    }
}